#include "bs.h"


i8 bs_eof(bs_t *bs)
{
	if (bs == NULL)
		return -1;
	return bs->cur == bs->end;
}

i8 bs_init(bs_t *bs, u8 *buf, u64 len)
{
	if (bs == NULL || buf == NULL)
		return -1;
	bs->start = buf;
	bs->end = buf + len;
	bs->cur = bs->start;
	bs->bit_offset = 8;
	return 0;
}


/// @brief 读取一bit数据
/// @param bs 
/// @return 
u32 bs_read1bit(bs_t *bs)
{
	u32 r = 0;
	bs->bit_offset--;
	if (bs_eof(bs) == 0)
	{
		r = (*(bs->cur) >> bs->bit_offset) & 0x01;
	}
	if (bs->bit_offset == 0)
	{
		bs->cur++;
		bs->bit_offset = 8;
	}
	return r;
}
/// @brief 读取n个bit
/// @param bs 
/// @param n 
/// @return 
u64 bs_readnbit(bs_t *bs, u64 n)
{
	u64 r = 0;
	for (u64 i = 0; i < n; i++)
	{
		// 从高位到低位放入r中
		r |= (bs_read1bit(bs) << (n - i - 1));
	}
	return r;
}



/// @brief 读取无符号整形
/// @param bs 
/// @return 
u64 bs_readue(bs_t *bs)
{
	u64 r = 0;
	u64 i = 0;
	// 读 0
	while (bs_read1bit(bs) == 0 && i < 32 && bs_eof(bs) == 0)
	{
		i++;
	}
	// 一个0表示 1bit
	r = bs_readnbit(bs, i);
	r += (1 << i) - 1;
	return r;
}

/// @brief 读取有符号整形
/// @param bs 
/// @return 
i64 bs_readse(bs_t *bs)
{
	// 读取数据
	i64 r = bs_readue(bs);
	// 解析符号
	if (r & 0x01)
	{
		r = (r + 1) / 2;
	}
	else
	{
		r = -(r / 2);
	}
	return r;
}
